package com.stars.easyms.datasource.pointcut;

import java.lang.annotation.Annotation;
import java.lang.reflect.Proxy;

import com.stars.easyms.base.util.AnnotationUtil;
import org.springframework.aop.ClassFilter;
import org.springframework.lang.NonNull;
import org.springframework.util.Assert;

/**
 * <p>className: EasyMsAnnotationClassFilter</p>
 * <p>description: EasyMs注解类过滤器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019/5/10 12:25
 */
final class EasyMsAnnotationClassFilter implements ClassFilter {

    private final Class<? extends Annotation> annotationType;

    private final boolean checkInherited;

    EasyMsAnnotationClassFilter(Class<? extends Annotation> annotationType, boolean checkInherited) {
        Assert.notNull(annotationType, "Annotation type must not be null");
        this.annotationType = annotationType;
        this.checkInherited = checkInherited;
    }

    @Override
    public boolean matches(@NonNull Class<?> clazz) {
        if (Proxy.isProxyClass(clazz)) {
            // 如果是mybatis的代理类则获取其父接口类判断
            Class<?>[] interfaceClasses = clazz.getInterfaces();
            if (interfaceClasses != null && interfaceClasses.length > 0) {
                for (Class<?> interfaceClass : interfaceClasses) {
                    if (this.checkInherited ? AnnotationUtil.hasAnnotation(interfaceClass, this.annotationType) : interfaceClass.isAnnotationPresent(this.annotationType)) {
                        return true;
                    }
                }
            }
        }
        return this.checkInherited ? AnnotationUtil.hasAnnotation(clazz, this.annotationType) : clazz.isAnnotationPresent(this.annotationType);
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        } else if (!(other instanceof EasyMsAnnotationClassFilter)) {
            return false;
        } else {
            EasyMsAnnotationClassFilter otherCf = (EasyMsAnnotationClassFilter) other;
            return this.annotationType.equals(otherCf.annotationType) && this.checkInherited == otherCf.checkInherited;
        }
    }

    @Override
    public int hashCode() {
        return this.annotationType.hashCode() * 40 + (checkInherited ? 1 : 0);
    }

    @Override
    public String toString() {
        return getClass().getName() + ": annotationType[" + this.annotationType + "], checkInherited[" + this.checkInherited + "]";
    }
}
